package model.base;
import java.util.ArrayList;
import java.util.Observable;

import model.algorithm.Action;
import model.algorithm.SearchDomain;
import model.algorithm.Searcher;

public class MyModel extends Observable implements Model {				// MyModel a sort of model and  is observable

	private Solution solution;
	private Searcher algo;
	private SearchDomain domain;
	private SearchAlgorithmFactory algFactory;
	private DomainFactory domainFactory;
	private SolutionManager solMan;
	
	public MyModel() {				// C'tor
		algFactory = new SearchAlgorithmFactory();
		domainFactory = new DomainFactory();
		solMan = SolutionManager.getInstance();
		solMan.loadSolutionsFromFile();
	}
	
	@Override
	public void selectDomain(String domainNamePlusStartingState) {			//operates the domainFactory --->creating domain
		domain = domainFactory.createDomain(domainNamePlusStartingState);
	}

	@Override
	public void selectAlgorithm(String algorithmNamePlusH) {				// operates the AlgorithmFactory ---> creating the algorithm
		algo = algFactory.createAlgorithm(algorithmNamePlusH); 
	}

	@Override
	public void solveDomain() {											// solves the domain
		String theProblem = domain.returnTheProblem() + algo.toString();
		if (!solMan.checkSolutionMap(theProblem)){
			ArrayList<Action> actions = algo.search(domain);
			solution = new Solution();
			solution.setActions(actions);
			// set theProblem in the solution!!!g
			solMan.addSolution(solution);
			this.setChanged();				// Raises the "changed" flag
			this.notifyObservers();			// notifies all the observers
		} else
			solution = solMan.getSolution(theProblem);
	}

	@Override
	public Solution getSolution() {		//returns the solution data member that its data is  made in solveDomain
		if (solution != null)
			return solution;
		else
		{	solveDomain();
		return solution;
		}
	}
}

